package com.fc.v2.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fc.v2.mapper.custom.SpiderDao;
import com.fc.v2.model.custom.spider.BuildingFloor;
import com.fc.v2.model.custom.spider.Developer;
import com.fc.v2.model.custom.spider.DeveloperBuildingList;
import com.fc.v2.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


/**
 * 自动生成代码Service
* @Title: GeneratorService.java
* @Package com.fc.v2.service
* @author fuce 
* @date 2019年5月9日 上午12:24:47
* @version V1.0 
 */
@Service
@SuppressWarnings("all")
public class SpiderService {
	private static Logger logger = LoggerFactory.getLogger(SpiderService.class);

	@Autowired
	private SpiderDao spiderDao;

	//获取列表的接口
	private String listUrl  = "https://yc.nxzhzj.cn/estateTradeR01/portals/query!listSalePermitProject";

	//开发商详情信息接口
	private String detailUrl = "https://yc.nxzhzj.cn/estateTradeR01/portals/query!queryProjPermitSale";

	//开发商预售套数接口
	private String preSaleNum = "https://yc.nxzhzj.cn/estateTradeR01/portals/query!statiPerSalePermitData";

	//开发商楼栋接口
	private String listBuildingsUrl = "https://yc.nxzhzj.cn/estateTradeR01/portals/query!listSalePermitBuild";

	//开发商楼层接口
	private String listRoomForTableUrl = "https://yc.nxzhzj.cn/estateTradeR01/portals/release!queryBldRoomForTable";


	private final static String limit  = "10";

	/**
	 * 爬取开发商列表
	 */
	public void getDevelopeList() {
		int page = 1;
		while(true) {
			//封装请求list接口的参数
			JSONObject a = new JSONObject();
			a.put("projectName", "");
			a.put("certNo", "");
			a.put("developer", "");

			Map param = new HashMap();
			param.put("page", page);
			param.put("limit", limit);
			param.put("jsonStr", a);
			String result = HttpClientUtil.doPost(listUrl + "?page=" + page, param);
			JSONObject jsonRes = JSONObject.parseObject(result);
			JSONArray jsonArray = (JSONArray) jsonRes.get("data");

			if (jsonArray.size() == 0) {
				break;
			}

			for (int i = 0; i < jsonArray.size(); i++) {
				JSONArray one = (JSONArray) jsonArray.get(i);
				String developeId = one.get(0) + "";
				String xukezhenghao = one.get(1) + "";
				Main(developeId, xukezhenghao);
				try {
					Thread.sleep(2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			page = page + 1;
		}
	}
	@Transactional
	public void Main(String developeId, String xukezhenghao) {
		//开发商信息
        Integer sets = getDevelopeLouNums(xukezhenghao);
        Developer developer = getDevelopeDetail(developeId);
        developer.setPreNum(sets);
        Developer developer1 = spiderDao.queryDevelopeById(developeId);

        //已存在的话 就执行更新
        if (Objects.equals(null, developer1)) {
			spiderDao.insertDeveloper(developer);
		} else {
			spiderDao.updateDevelope(developer);
		}

        //开发商楼栋信息
		List<DeveloperBuildingList> developerBuildingLists = getDevelopeBuildings(developeId);
		Map map = new HashMap();
		map.put("developerId", developeId);
		map.put("list", developerBuildingLists);
		//删除原有的，插入新的
		spiderDao.deleteDeveloperBuildingList(developeId);
		spiderDao.insertDeveloperBuildingList(map);

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//具体楼层信息
		for (DeveloperBuildingList build: developerBuildingLists) {
			Map map1 = new HashMap();
			map1.put("buildId", build.getBuildId());
			map1.put("list", build.getBuildingFloors());
			//删除原有的，插入新的
			spiderDao.deleteBuildingFloors(build.getBuildId());
			spiderDao.insertFloors(map1);
		}

    }

	/**
	 * 爬取开发商楼栋列表
     * 及其每一个楼栋的 所有楼层信息
	 */
	public List<DeveloperBuildingList> getDevelopeBuildings(String developeId) {
		List<DeveloperBuildingList> developerBuildingLists = new ArrayList<>();
		int page = 1;
        //封装请求list接口的参数
        JSONObject a = new JSONObject();
        a.put("cert_id", developeId);
        Map param = new HashMap();
        param.put("page", page);
        param.put("limit", limit);
        param.put("jsonStr", a);
        String result = null;
        try {
            result = HttpClientUtil.doPost(listBuildingsUrl + "?jsonStr=" + URLEncoder.encode(a.toJSONString(), "UTF-8"), param);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject jsonRes = JSONObject.parseObject(result);
        JSONArray jsonArray = (JSONArray) jsonRes.get("data");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray one = (JSONArray) jsonArray.get(i);
            DeveloperBuildingList developerBuildingList = new DeveloperBuildingList();
            developerBuildingList.setBuildId(one.getString(0));
            developerBuildingList.setDeveloperId(developeId);
            developerBuildingList.setZhuangMingChen(one.getString(2));
            developerBuildingList.setLouDongLeiXing(one.getString(3));
            developerBuildingList.setXuHao(one.getInteger(6));
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            List<BuildingFloor> buildingFloors = getBldRoomForTable(developerBuildingList.getBuildId(),
                    developerBuildingList.getDeveloperId());
            developerBuildingList.setBuildingFloors(buildingFloors);
			developerBuildingLists.add(developerBuildingList);
        }
        return developerBuildingLists;
	}

	/**
	 *
     * 爬取每一个楼栋的 所有楼层信息
	 */
	public List<BuildingFloor> getBldRoomForTable(String buildId, String developeId) {

        List<BuildingFloor> BuildingFloors = new ArrayList<>();
        //封装请求list接口的参数
        JSONObject a = new JSONObject();
        a.put("buildId", buildId);
        Map param = new HashMap();
        param.put("jsonStr", a);
        String result = null;
        try {
            result = HttpClientUtil.doPost(listRoomForTableUrl + "?jsonStr=" + URLEncoder.encode(a.toJSONString(), "UTF-8"), param);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject jsonRes = JSONObject.parseObject(result);
        String floorCount = jsonRes.getString("floorCount").split(",")[1];
        JSONArray data = (JSONArray) jsonRes.get("data");
        JSONArray floorData = (JSONArray) jsonRes.get("floorData");
        for (int j = 0; j < floorData.size(); j++) {
            JSONObject obj = (JSONObject) floorData.get(j);
            Set<String> keys = obj.keySet();
            for (String key: keys) {
                String[] floors = obj.getString(key).split(",");
                for (int i = 0; i < floors.length; i++) {
                    int f = Integer.valueOf(floors[i]);
                    JSONArray realFloor = (JSONArray) data.get(f);
                    BuildingFloor buildingFloor = new BuildingFloor();
                    buildingFloor.setDeveloperId(developeId);
                    buildingFloor.setBuildId(buildId);
                    buildingFloor.setZongCengShu(floorCount);
                    buildingFloor.setQianYueStatus(realFloor.get(9) + "");
                    buildingFloor.setDanJia(realFloor.get(16) + "");
                    buildingFloor.setMianJi(realFloor.get(6) + "");
                    buildingFloor.setLouCeng(realFloor.get(0) + "");
                    buildingFloor.setDanYuan(realFloor.get(3) + "");
                    buildingFloor.setLouCengInfo(realFloor.get(1) + "");
                    BuildingFloors.add(buildingFloor);
                }
            }
        }
        return BuildingFloors;
	}

	/**
	 * 爬取开发商详情
	 */
	public Developer getDevelopeDetail(String developeId) {
		//封装请求list接口的参数
		Map param = new HashMap();
		param.put("id", developeId);
		String result = HttpClientUtil.doPost(detailUrl + "?id=" + developeId, param);
		JSONObject jsonRes = JSONObject.parseObject(result);
		JSONArray detail = (JSONArray) jsonRes.get("data");
		detail = (JSONArray) detail.get(0);
        Developer developer = new Developer();
        developer.setDeveloperId(developeId);
        developer.setKaiFaShang(detail.getString(0));
        developer.setXiangMuMingZi(detail.getString(1));
        developer.setZongMianJi(detail.getString(2));
        developer.setFaZhengShiJian(detail.getString(3));
        developer.setXiangMuWeiZhi(detail.getString(4));
        developer.setXiangMuLeiXing(detail.getString(5));
        developer.setXiangMuZhuangTai(detail.getString(6));
        developer.setYuShouZhengHao(detail.getString(7));
        developer.setTuDiShiYongQuan(detail.getString(8));
        developer.setTuDiQuanZhengLeiXing(detail.getString(9));
        developer.setQiShiRiQi(detail.getString(10));
        developer.setZhongZhiRiQi(detail.getString(11));
        developer.setShiGongXuKeZheng(detail.getString(12));
        developer.setGuiHuaXuKeZheng(detail.getString(13));
        developer.setYuShouMianJi(detail.getString(14));
        developer.setSytdsyqQiShiRiQi(detail.getString(16));
        developer.setSytdsyqZhongZhiRiQi(detail.getString(17));
        developer.setZiJiJianGuanZhangHu(detail.getString(18));
        developer.setZiJiJianGuanZhangHao(detail.getString(19));
		return developer;
	}

	/**
	 * 爬取开发商楼栋个数
	 */
	public Integer getDevelopeLouNums(String xukezhenghao) {
		//封装请求list接口的参数
		Map param = new HashMap();
		param.put("certno", xukezhenghao);
		//?certno=" + URLEncoder.encode("（银审服）预售证第 20210495号", "UTF-8")
		String result = null;
		try {
			result = HttpClientUtil.doPost(preSaleNum + "?certno=" + URLEncoder.encode(xukezhenghao, "UTF-8"), param);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		JSONObject jsonRes = JSONObject.parseObject(result);
		JSONObject detail = (JSONObject) jsonRes.get("data");
		try  {
			return detail.getIntValue("shopSets");
		} catch (Exception ex) {
			return 0;
		}
	}

	public static void main(String[] args) {
		new SpiderService().getDevelopeList();
	}
}
